#include "mainwindow.h"
#include "./ui_mainwindow.h"
#include "turntable.h"
#include <QHBoxLayout>
#include <QPalette>
#include <QThread>
#include <QDebug>
#include <QRandomGenerator>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    setWindowFlag(Qt::FramelessWindowHint);     // 设置无边框

    setAttribute(Qt::WA_TranslucentBackground,true); //背景透明
    setStyleSheet("border: none;");

    // 添加转盘和指针
    addTurnTable("://turntable.png");
    addPointer("://pointer.png");
    // 添加关闭按钮
    addCloseButton();

    // 禁用 m_TurnTable子控件的鼠标事件，防止父窗体鼠标拖拽失效
    m_TurnTable->setAttribute(Qt::WA_TransparentForMouseEvents, true);

    connect(m_Pointer, SIGNAL(clicked()), this, SLOT(rotation()));

    setFixedSize(630, 600);
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::addTurnTable(QString pixmapPath)
{
    m_TurnTable = new QWidget(ui->centralwidget);

    m_TurnTable->setFixedSize(600,600);

    QHBoxLayout* layout = new QHBoxLayout(m_TurnTable);
    layout->setAlignment(Qt::AlignCenter);

    TurnTable* tt = new TurnTable;

    tt->loadPicture(pixmapPath);

    // 创建一个QGraphicsScene
    m_Scene = new QGraphicsScene;
    // 创建一个QGraphicsProxyWidget，将QWidget嵌入其中
    m_Proxy = m_Scene->addWidget(tt);

    // 设置旋转中心为QGraphicsProxyWidget的中心
    m_Proxy->setTransformOriginPoint(m_Proxy->boundingRect().center());

    // 创建一个QGraphicsView来展示场景
    m_View = new QGraphicsView(m_Scene);


    // 确保QGraphicsView没有默认的背景颜色
    m_View->setStyleSheet("background-color: transparent;");

    // 设置水平和垂直滚动条策略为始终关闭
    m_View->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    m_View->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);

    layout->addWidget(m_View);

    int tCenter_x = this->width() / 2;
    int tCenter_y = this->height() / 2;

    int tPos_x = tCenter_x - m_TurnTable->width() / 2;
    int tPos_y = tCenter_y - m_TurnTable->height() / 2;

    m_TurnTable->move(tPos_x, tPos_y);

    update();

}

void MainWindow::addPointer(QString pixmapPath)
{
    m_Pointer = new QPushButton(ui->centralwidget);

    float width = QPixmap(pixmapPath).size().width();
    float height = QPixmap(pixmapPath).size().height();

    m_Pointer->setFixedSize(100, height / width * 100);
    m_Pointer->setIcon(QIcon(QPixmap(pixmapPath)));
    m_Pointer->setIconSize(m_Pointer->size());

    int tCenter_x = this->width() / 2;
    int tCenter_y = this->height() / 2;

    int tPos_x = tCenter_x - m_Pointer->width() / 2;
    int tPos_y = tCenter_y - m_Pointer->height() / 2;

    m_Pointer->move(tPos_x + 7, tPos_y - 20);
    update();
}

void MainWindow::addCloseButton()
{
    // 创建关闭按钮
    m_CloseButton = new QPushButton(this);
    m_CloseButton->setText("×"); // 设置按钮文本为叉叉
    m_CloseButton->setFixedSize(30, 30); // 设置按钮大小

    // 设置按钮样式
    m_CloseButton->setStyleSheet(
        "QPushButton {"
        "   background-color: red;"
        "   color: white;"
        "   border-radius: 15px;"
        "   font-size: 18px;"
        "}"
        "QPushButton:hover {"
        "   background-color: darkred;"
        "}"
        );

    // 设置按钮位置（右上角）
    int x = this->width() - m_CloseButton->width() - 10; // 距离右边 10 像素
    int y = 10; // 距离顶部 10 像素
    m_CloseButton->move(x, y);

    // 连接按钮的点击信号到关闭窗口的槽
    connect(m_CloseButton, &QPushButton::clicked, this, &MainWindow::close);
}

void MainWindow::rotation()
{
    if (m_Flag) return;
    // 生成 [min, max) 的随机整数
    int randomIntInRange = QRandomGenerator::global()->bounded(100, 150);

    // 设置旋转中心为图元的中心
    m_Proxy->setTransformOriginPoint(m_Proxy->boundingRect().center());

    float angle = 0.0f;
    int interval = INTERVAL * 2;
    // 加速
    for (int n = 0; n < randomIntInRange; ++n) {
        m_Flag = true;
        if ((int)angle < MAX_SPEED) {
            angle += 0.5f;
            if (interval > INTERVAL) interval--;
            QThread::msleep(interval); // 模拟耗时操作
        } else {
            QThread::msleep(INTERVAL); // 模拟耗时操作
        }
        m_Proxy->setRotation(m_Proxy->rotation() + angle); // 每次递增 1 度

        // 更新场景和视图
        QCoreApplication::processEvents();
        m_Scene->update();
        m_View->viewport()->update(); // 确保视图也更新
    }

    // 减速
    for (int n = 0; n < randomIntInRange; ++n) {
        m_Flag = true;
        if ( randomIntInRange - n  <= 2 * MAX_SPEED ) {
            angle -= 0.5f;
            if (interval < 2 * INTERVAL) interval++;
            QThread::msleep(interval); // 模拟耗时操作
        } else {
            QThread::msleep(INTERVAL); // 模拟耗时操作
        }
        m_Proxy->setRotation(m_Proxy->rotation() + angle); // 每次递增 1 度
        // 更新场景和视图
        QCoreApplication::processEvents();
        m_Scene->update();
        m_View->viewport()->update(); // 确保视图也更新
    }
    m_Flag = false;
}

void MainWindow::mousePressEvent(QMouseEvent *event)
{
    if (event->button() == Qt::LeftButton) {
        isDragging = true;
        dragStartPosition = event->globalPos() - frameGeometry().topLeft();
        event->accept();
    }
}

void MainWindow::mouseMoveEvent(QMouseEvent *event)
{
    if (isDragging && (event->buttons() & Qt::LeftButton)) {
        move(event->globalPos() - dragStartPosition);
        event->accept();
    }
}

void MainWindow::mouseReleaseEvent(QMouseEvent *event)
{
    if (event->button() == Qt::LeftButton) {
        isDragging = false;
        event->accept();
    }
}

void MainWindow::resizeEvent(QResizeEvent *event)
{
    QMainWindow::resizeEvent(event);

    if (m_CloseButton) {
        int x = this->width() - m_CloseButton->width();
        int y = 70;
        m_CloseButton->move(x, y);
    }
}

